package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.QueryPageDTO;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author Yan
 * @date 2022/2/21
 */
@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    //以前注入EmployeeMapper，现在不用了，ServiceImpl已经帮我们注入了
    //核心登录业务

    /**
     * 登录
     * @param employee 员工
     * @return
     */
    @Override
    public Result<Employee> login(Employee employee) {
        //1. 参数校验
        if (ObjectUtils.isEmpty(employee)) {
            return Result.error("登录失败");
        }

        //校验对象中属性（用户名和密码）
        if (ObjectUtils.isEmpty(employee.getUsername()) || ObjectUtils.isEmpty(employee.getPassword())) {
            return Result.error("登录失败");
        }

        //2.1 密码加密
        String password = employee.getPassword();

        String encodePassword = DigestUtils.md5DigestAsHex(password.getBytes());

        //2.2 根据用户查询数据库
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        Employee dbEmployee = this.getOne(wrapper);

        if (ObjectUtils.isEmpty(dbEmployee)) {
            return Result.error("登录失败");
        }

        if (ObjectUtils.isEmpty(dbEmployee.getPassword())) {
            return Result.error("登录失败");
        }

        //2.3 密码对比
        if (!dbEmployee.getPassword().equals(encodePassword)) {
            return Result.error("登录失败");
        }

        //2.4 检查用户状态
        if (dbEmployee.getStatus() == 0) {
            return Result.error("登录失败");
        }
        //3. 数据封装返回

        dbEmployee.setPassword("");

        return Result.success(dbEmployee);
    }

    /**
     * 添加员工方法
     *
     * @param employee 对象
     * @return
     */
    @Transactional
    @Override
    public Result<String> saveEmployee(Employee employee) {
        if (ObjectUtils.isEmpty(employee)){
            return Result.error("数据有误");
        }
        //对象属性校验
        if (ObjectUtils.isEmpty(employee.getUsername())
                ||ObjectUtils.isEmpty(employee.getIdNumber())
                ||ObjectUtils.isEmpty(employee.getName())
                ||ObjectUtils.isEmpty(employee.getPhone())){
            return Result.error("参数不对");
        }

        log.info("新员工的信息是:" + employee.toString());
        //设置默认密码
        String encodePassword = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(encodePassword);

        //employee.setStatus(1);
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());


        this.save(employee);

        return Result.success("添加成功");

    }

    /**
     * 分页查询
     * @param queryPageDTO 分页数据类
     * @return
     */
    @Override
    public Result<Page<Employee>> page(QueryPageDTO queryPageDTO) {

        System.out.println("分页数据："+queryPageDTO);


        Long currentPage = queryPageDTO.getPage();
        Long pageSize = queryPageDTO.getPageSize();
        String name = queryPageDTO.getName();

        if (ObjectUtils.isEmpty(currentPage)||currentPage<=0){
            currentPage = 1L;
        }
        if (ObjectUtils.isEmpty(pageSize)||pageSize<=0){
            pageSize = 10L;
        }


        Page<Employee> page = new Page<>(currentPage,pageSize);

        LambdaQueryWrapper<Employee> wrapper =new LambdaQueryWrapper<>();

        //1.如果参数1，为true，会使用当前条件，false不使用当前条件
        wrapper.like(StringUtils.isNotBlank(name),Employee::getName,name);

        this.page(page,wrapper);


        return Result.success(page);
    }

    /**
     * 根据id修改员工
     * @param employee
     * @return
     */
    @Override
    @Transactional
    public Result<String> update(Employee employee) {
        //参数校验
        if (ObjectUtils.isEmpty(employee)){
            return Result.error("数据有误");
        }

        System.out.println(employee+"..............................");

        //employee.setUpdateTime(LocalDateTime.now());

        if (this.updateById(employee)){
            return Result.success("修改成功");
        }

        return Result.error("修改失败啦");

    }

    /**
     * 根据id查员工
     * @param id
     * @return
     */
    @Override
    public Result<Employee> getEmployeeById(Long id) {
        if (ObjectUtils.isEmpty(id)){
            return Result.error("id不能是空");
        }


        Employee byId = this.getById(id);

        if (ObjectUtils.isEmpty(byId)){
            return Result.error("没查到员工信息");
        }

        return Result.success(byId);
    }

    @Override
    public Result<String> updateEmployeeStatusById(Employee employee){
        if (ObjectUtils.isEmpty(employee)){
            return Result.error("参数有问题");
        }

        Integer status = employee.getStatus();
        Long employeeId = employee.getId();

        if (ObjectUtils.isEmpty(employeeId)){
            return Result.error("参数有问题");
        }

        if (ObjectUtils.isEmpty(status)){
            return Result.error("参数有问题");
        }

        boolean flag=(status ==1||status == 0);
        if (!flag){
            return Result.error("参数有问题");

        }

        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getId,employeeId);
        Employee dbEmployee = this.getOne(wrapper);
        if (ObjectUtils.isEmpty(dbEmployee)){
            return Result.error("数据有问题");
        }
        Integer dbStatus = dbEmployee.getStatus();
        //如果数据库中的状态，和用户输入的状态一样，没必要修改
        if (status.equals(dbStatus)){
            return Result.error("数据有问题");
        }

        dbEmployee.setStatus(status);
        //更新状态
        this.updateById(dbEmployee);
        return Result.success("更新成功");
    }
}
